package com.module.wx.controller;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.module.wx.domain.*;
import com.module.wx.service.IZzdOrderInfoService;
import com.module.wx.service.IZzdShoppingCartInfoService;
import com.module.wx.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.module.wx.service.IZzdShoppingCartService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author hezhengxian
 * @date 2023-02-14
 */
@RestController
@RequestMapping("/shopping")
public class ZzdShoppingCartController extends BaseController
{
    @Autowired
    private IZzdShoppingCartService zzdShoppingCartService;
    @Autowired
    private IZzdShoppingCartInfoService zzdShoppingCartInfoService;
    @Autowired
    private IZzdOrderInfoService zzdOrderInfoService;

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("wx:shopping:list")
    @GetMapping("/list")
    public TableDataInfo list(ZzdShoppingCart zzdShoppingCart)
    {
        startPage();
        List<ZzdShoppingCart> list = zzdShoppingCartService.selectZzdShoppingCartList(zzdShoppingCart);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("wx:shopping:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZzdShoppingCart zzdShoppingCart)
    {
        List<ZzdShoppingCart> list = zzdShoppingCartService.selectZzdShoppingCartList(zzdShoppingCart);
        ExcelUtil<ZzdShoppingCart> util = new ExcelUtil<ZzdShoppingCart>(ZzdShoppingCart.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @RequiresPermissions("wx:shopping:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(zzdShoppingCartService.selectZzdShoppingCartById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @RequiresPermissions("wx:shopping:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZzdShoppingCart zzdShoppingCart)
    {
        return toAjax(zzdShoppingCartService.insertZzdShoppingCart(zzdShoppingCart));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("wx:shopping:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZzdShoppingCart zzdShoppingCart)
    {
        return toAjax(zzdShoppingCartService.updateZzdShoppingCart(zzdShoppingCart));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("wx:shopping:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(zzdShoppingCartService.deleteZzdShoppingCartByIds(ids));
    }

    /**
     * 用户加入购物车,添加主从表信息,需判断对应用户购物车及购物车商品信息是否存在
     */
    @RequiresPermissions("wx:shopping:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PutMapping("/addShoppingList")
    public AjaxResult addShoppingList(@RequestBody ZzdShoppingCart zzdShoppingCart)
    {
        AjaxResult ajax = new AjaxResult();
        Map<String,String> map = new HashMap<>();
        if(zzdShoppingCart!=null){
            // 判断同一用户是否在相同商家添加购物车商品
            map.put("userId",zzdShoppingCart.getUserId());
            map.put("storeId",zzdShoppingCart.getStoreId());
            List<ZzdShoppingCart> zzdShoppingCartList = zzdShoppingCartService.selectZzdShoppingCartByUserIdAndStoreId(map);
            // 判断用户之前是否将该商家商品加入过购物车
            if(zzdShoppingCartList.size()>0){
                // 如果存在更新信息，订单总金额累加
                ZzdShoppingCart shoppingCart = zzdShoppingCartList.get(0);
                // 累加购物车金额
                // shoppingCart.setOrderPric(shoppingCart.getOrderPric().add(zzdShoppingCart.getOrderPric()));
                zzdShoppingCartService.updateZzdShoppingCart(shoppingCart);
                // 判断子表商品是否存在
                if(zzdShoppingCart.getCartInfoList().size()>0){
                    for (int i = 0; i < zzdShoppingCart.getCartInfoList().size(); i++) {
                        Map<String,String> mapInfo = new HashMap<>();
                        map.put("userId",zzdShoppingCart.getCartInfoList().get(i).getUserId());
                        map.put("orderId",zzdShoppingCart.getCartInfoList().get(i).getOrderId());
                        map.put("orderType",zzdShoppingCart.getCartInfoList().get(i).getOrderType());
                        List<ZzdShoppingCartInfo> zzdShoppingCartInfoList = zzdShoppingCartInfoService.selectZzdShoppingCartByUserIdAndStoreId(map);
                        // 如果用户加购了该商品
                        if(zzdShoppingCartInfoList.size()>0){
                            // 数量累加
                            ZzdShoppingCartInfo zzdCartInfo = zzdShoppingCartInfoList.get(0);
                            // zzdCartInfo.setOrderPric(zzdCartInfo.getOrderPric().add(zzdShoppingCart.getCartInfoList().get(i).getOrderPric()));
                            zzdCartInfo.setOrderNum(zzdCartInfo.getOrderNum()+zzdShoppingCart.getCartInfoList().get(i).getOrderNum());
                            zzdCartInfo.setUpdtTime(new Date());
                            zzdShoppingCartInfoService.updateZzdShoppingCartInfo(zzdCartInfo);
                        }else{
                            zzdShoppingCart.getCartInfoList().get(i).setId(Util.get_radom_id());
                            zzdShoppingCart.getCartInfoList().get(i).setUpdtTime(new Date());
                            zzdShoppingCart.getCartInfoList().get(i).setShoppingId(shoppingCart.getId());
                            zzdShoppingCart.getCartInfoList().get(i).setIsDel("0");
                            zzdShoppingCartInfoService.insertZzdShoppingCartInfo(zzdShoppingCart.getCartInfoList().get(i));
                        }
                    }
                }
            }else{
                // 如果不存在，则添加购物车信息
                // 添加随机id，创建时间
                zzdShoppingCart.setId(Util.get_radom_id());
                zzdShoppingCart.setCrteTime(new Date());
                // 更改为购物车状态未购买状态
                zzdShoppingCart.setIsShopping("0");
                zzdShoppingCartService.insertZzdShoppingCart(zzdShoppingCart);
                //添加子表信息
                if(zzdShoppingCart.getCartInfoList().size()>0){
                    for (int i = 0; i < zzdShoppingCart.getCartInfoList().size(); i++) {
                        ZzdShoppingCartInfo zzdShoppingCartInfo = zzdShoppingCart.getCartInfoList().get(i);
                        zzdShoppingCartInfo.setId(Util.get_radom_id());
                        zzdShoppingCartInfo.setUpdtTime(new Date());
                        zzdShoppingCartInfo.setShoppingId(zzdShoppingCart.getId());
                        zzdShoppingCartInfo.setIsDel("0");
                        zzdShoppingCartInfoService.insertZzdShoppingCartInfo(zzdShoppingCartInfo);
                    }
                }
            }
            ajax.put("msg","操作成功");
            ajax.put("code",200);
        }
        return ajax;
    }

    /**
     * 根据用户id查询购物车信息
     */
    @RequiresPermissions("wx:shopping:list")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/selecShoppingInfo/{userId}")
    public AjaxResult selectShoppingInfoByUserId(@PathVariable("userId")String userId) throws SQLException, ClassNotFoundException {
        AjaxResult ajax = AjaxResult.success();
        if(userId !=null&&!userId.equals("")){
            List<ZzdShoppingCart> zzdShoppingCartList = zzdShoppingCartService.selectZzdShoppingCartByUserId(userId);
            if(zzdShoppingCartList.size()>0){
                for (int i = 0; i < zzdShoppingCartList.size(); i++) {
                    List<ZzdShoppingCartInfo> list = zzdShoppingCartInfoService.selectZzdShoppingCartByShoppingId(zzdShoppingCartList.get(i).getId());
                    // 实时计算购物车价格
                    for (int j = 0; j < list.size(); j++) {
                        // 根据商品id和商品规格查询商品价格
                        ZzdOrderInfo orderInfo = zzdOrderInfoService.selectZzdOrderInfoById(list.get(j).getOrderId());
                        // 如果菜品id存在
                        if(orderInfo!=null){
                            // 如果该菜品没有规格类型
                            if(orderInfo.getOrderType()==null||orderInfo.getOrderType().equals("")){
                                // 商品总价为（商品数量*商品单价）
                                list.get(j).setOrderPric(orderInfo.getOrderPrice().multiply(new BigDecimal(list.get(j).getOrderNum())));
                            }else{
                                // 该商品是否有多种规格
                                if(orderInfo.getOrderType().contains(",")==true){
                                    for (int k = 0; k < orderInfo.getOrderType().split(",").length; k++) {
                                        // 如果是该种规格
                                        if(orderInfo.getOrderType().split(",")[k].split("-")[0].equals(list.get(j).getOrderType())){
                                            list.get(j).setOrderPric(new BigDecimal(orderInfo.getOrderType().split(",")[k].split("-")[1]).multiply(new BigDecimal(list.get(j).getOrderNum())));
                                        }
                                    }
                                }else{
                                    // 如果只有一种规格
                                    list.get(j).setOrderPric(new BigDecimal(orderInfo.getOrderType().split("-")[1]).multiply(new BigDecimal(list.get(j).getOrderNum())));
                                }
                            }
                        }
                    }
                    zzdShoppingCartList.get(i).setCartInfoList(list);
                }
            }

            ajax.put("zzdShoppingCartList",zzdShoppingCartList);
        }
        return ajax;
    }

    /**
     *  根据商家id删除购物信息
     * @param param
     * @return
     */
    @RequiresPermissions("wx:shopping:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeShoppingList")
    public AjaxResult removeShoppingList(@RequestBody Map<String,String[]> param)
    {
        AjaxResult ajax = new AjaxResult();
        String[] mainNodes = null;
        String[] childNodes = null;
        if(param!=null){
            // 传入的主表参数
            mainNodes = param.get("mainNodes");
            // 子表参数
            childNodes = param.get("childNodes");
            // 需删除的订单编号不为空且长度不为0
            if(mainNodes!=null&&mainNodes.length>0){
                for (int i = 0; i < mainNodes.length; i++) {
                    ZzdShoppingCart zzdShoppingCart = zzdShoppingCartService.selectZzdShoppingCartById(mainNodes[i]);
                    if(zzdShoppingCart!=null){
                        // 删除订单信息
                        zzdShoppingCart.setIsShopping("2");
                        zzdShoppingCartService.updateZzdShoppingCart(zzdShoppingCart);
                    }
                }
            }
            // 根据主订单批量删除子购物车信息
            if(childNodes!=null&&childNodes.length>0){
                for (int i = 0; i < childNodes.length; i++) {
                    ZzdShoppingCartInfo zzdShoppingCartInfo = zzdShoppingCartInfoService.selectZzdShoppingCartInfoById(childNodes[i]);
                    if(zzdShoppingCartInfo!=null){
                        zzdShoppingCartInfo.setIsDel("1");
                        zzdShoppingCartInfoService.updateZzdShoppingCartInfo(zzdShoppingCartInfo);
                    }
                }
            }
            ajax.put("msg","操作成功");
            ajax.put("code",200);
        }
        return ajax;
    }

    /**
     * 用户修改购物车信息
     */
    @RequiresPermissions("wx:shopping:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PutMapping("/updateShoppingList")
    public AjaxResult updateShoppingList(@RequestBody List<ZzdShoppingCart> zzdShoppingCartList){
        AjaxResult ajax = new AjaxResult();
        if(zzdShoppingCartList.size()>0){
            for (int i = 0; i < zzdShoppingCartList.size(); i++) {
                ZzdShoppingCart zzdShoppingCart = zzdShoppingCartList.get(i);
                if(zzdShoppingCart.getCartInfoList().size()>0){
                    for (int j = 0; j < zzdShoppingCart.getCartInfoList().size(); j++) {
                        // 更新子表数据
                        zzdShoppingCartInfoService.updateZzdShoppingCartInfo(zzdShoppingCart.getCartInfoList().get(j));
                    }
                    // 更新主表数据
                    zzdShoppingCartService.updateZzdShoppingCart(zzdShoppingCart);
                }
            }
        }else{
            ajax.put("msg","未做任何修改");
            ajax.put("code",200);
        }
        return ajax;
    }
}
